package com.gocoolmall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.gocoolmall.common.to.mq.SeckillOrderTo;
import com.gocoolmall.common.utils.R;
import com.gocoolmall.common.vo.MemberRespVo;
import com.gocoolmall.seckill.feign.CouponFeignService;
import com.gocoolmall.seckill.feign.ProductFeignService;
import com.gocoolmall.seckill.interceptor.LoginUserInterceptorRegistry;
import com.gocoolmall.seckill.service.SeckillService;
import com.gocoolmall.seckill.to.SeckillSkuRedisTo;
import com.gocoolmall.seckill.vo.SeckillSessionsWithSkusVo;
import com.gocoolmall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;
    //
    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:Sku:";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//+商品随机码

    @Override
    public void uploadSeckillSkuLatest3Day() {
        //1.扫描最近三天需要参与秒杀的活动
        R session = null;
        try {
            session = couponFeignService.getLate3DaySession();
        } catch (Exception e) {
            e.printStackTrace();
            throw new NullPointerException("Coupon容器接口/coupon/seckillsession/lates3DaySession没有上线");
        }
        if (session.getCode() == 0) {
            //上架商品
            List<SeckillSessionsWithSkusVo> sessions = session.getDate(new TypeReference<List<SeckillSessionsWithSkusVo>>() {
            });
            log.info("上架商品" + JSONObject.toJSONString(sessions));
            //缓存到redis
            //1、缓存活动信息
            saveSessionInfos(sessions);
            //2、缓存活动的关联商品信息
            saveSessionSkuInfos(sessions);
        }

    }
    public List<SeckillSkuRedisTo> blockHandler(BlockException e){
        log.error("getCurrentSeckillSkuResource被限流了");
        return null;
    }

    /**
<<<<<<< HEAD
=======
     *返回当前时间可以参加的秒杀的商品信息
>>>>>>> kill
     * @return
     */
    @SentinelResource(value = "getCurrentSeckillSkuResource" ,blockHandler = "blockHandler")
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //1、确定当前时间属于哪个秒杀场次
        long time = new Date().getTime();
<<<<<<< HEAD

        try (Entry entry = SphU.entry("seckillSkes")){
            Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            for (String key : keys) {
                String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                long start = Long.parseLong(s[0]);
                long end = Long.parseLong(s[1]);
                if (time >= start && time <= end) {
                    //2、获取这个秒杀场次需要的所有商品信息
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<String> list = hashOps.multiGet(range);
                    if (list != null) {
                        List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                            SeckillSkuRedisTo seckillSkuRedisTo = new SeckillSkuRedisTo();
                            SeckillSkuRedisTo redisTo = JSON.parseObject(item.toString(), SeckillSkuRedisTo.class);
                            //                        redisTo.setRandomCode("");//当前秒杀开始就需要随机码
                            return redisTo;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                    break;
=======
        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key:keys){
            //seckill:session:12342345_342342340000
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            long start = Long.parseLong(s[0]);
            long end = Long.parseLong(s[1]);
            if (time >= start && time <= end) {
                //2、获取这个秒杀场次需要的所有商品信息
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> list = hashOps.multiGet(range);
                System.out.println("获取这个秒杀场次需要的所有商品信息:"+JSONObject.toJSONString(list));
                if (list != null){
                    List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                        SeckillSkuRedisTo redisTo = JSON.parseObject((String)item, SeckillSkuRedisTo.class);
//                        redisTo.setRandomCode("");//当前秒杀开始就需要随机码
                        return redisTo;
                    }).collect(Collectors.toList());
                    return collect;
>>>>>>> kill
                }

            }
        } catch (BlockException e) {
            log.error("资源被限流,{}",e.getMessage());
        }
        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //1、找到所有需要参与秒杀的商品
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
<<<<<<< HEAD
        if (keys != null && keys.size() > 0) {
            String regx = "\\d." + skuId;
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
=======
        if (keys != null && keys.size() > 0){
            String regx = "\\d_"+skuId;
            for (String key:keys){
                //6_3
                if (Pattern.matches(regx,key)){
>>>>>>> kill
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo skuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    //随机码
                    long current = new Date().getTime();
                    Long startTime = skuRedisTo.getStartTime();
                    Long endTime = skuRedisTo.getEndTime();
<<<<<<< HEAD
                    if (current >= startTime && current <= endTime) {
=======
                    if (current >= startTime && current <= endTime){
>>>>>>> kill

                    } else {
                        skuRedisTo.setRandomCode(null);
                    }
                    return skuRedisTo;
                }
            }
        }
        return null;
    }

    //TODO 上架秒杀商品的时候，每一个数据都有过期时间。
    //TODO 秒杀后续的流程，简化了收货地址等信息。

    @Override
    public String kill(String killId, String key, Integer num) {
        long sstart = System.currentTimeMillis();
        //获取用户信息
        MemberRespVo respVo = LoginUserInterceptorRegistry.loginUser.get();
        //1、获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        log.info("杀商品的详细信息:{}",hashOps);
        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        } else {
            SeckillSkuRedisTo redis = JSON.parseObject(json, SeckillSkuRedisTo.class);
            //校验合法性
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            long ttl = endTime - startTime;
            long time = new Date().getTime();
            //1、校验时间的合法性
            if (time >= startTime && time <= endTime) {
                //2、校验随机码和商品id
                String randomCode = redis.getRandomCode();
                String skuId = redis.getPromotionSessionId() + "_" + redis.getSkuId();
                if (randomCode.equals(key) && killId.equals(skuId)) {
                    //3、验证购物数量是否合理
                    log.info("验证购物数量是否合理num:"+num+"::::::::::redis.getSeckillLimit:"+redis.getSeckillLimit());
                    if (num <= redis.getSeckillLimit()) {
                        //4、验证这个人是否已经购买过了。幂等性：如果只要秒杀成功，就去占位。userId_SessionId_sku
                        String redisKey = respVo.getId() + "_" + skuId;
                        //自动过期
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //占位成功说明从来没有买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            //boolean b = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                            boolean b = semaphore.tryAcquire(num);
                            log.info("占位返回状态："+b);
                            if (b) {
                                //秒杀成功
                                //快速下单。发送MQ消息。 10ms TODO
                                String timeId = IdWorker.getTimeId();
                                System.out.println("单号："+timeId);
                                SeckillOrderTo orderTo = new SeckillOrderTo();
                                orderTo.setOrderSn(timeId);
                                orderTo.setMemberId(respVo.getId());
                                orderTo.setNum(num);
                                orderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                orderTo.setSkuId(redis.getSkuId());
                                orderTo.setSeckillPrice(redis.getSeckillPrice());
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderTo);
                                long send = System.currentTimeMillis();
                                log.info("秒杀使用时间: {}ms",(send-sstart));
                                log.info("秒杀单号："+timeId);
                                return timeId;
                            } else {
                                return null;
                            }

                        } else {
                            //说明已经买个了
                            return null;
                        }
                    } else {
                        return null;
                    }
                } else {
                    return null;
                }
            } else {
                return null;
            }
        }
    }

    //1、缓存活动信息
    private void saveSessionInfos(List<SeckillSessionsWithSkusVo> sessions) {
        if(sessions != null)
        sessions.stream().forEach(session -> {
            Long startTime = session.getStartTime().getTime();
            Long endTime = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
            log.info("缓存活动信息key:" + key);
            if (!redisTemplate.hasKey(key)) {
                List<String> collect = session.getRelationSkus().stream().map(item ->
                        item.getPromotionSessionId().toString() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                log.info("活动信息" + JSONObject.toJSONString(collect));
                //缓存活动信息
                if (collect.size() > 0) {
                    redisTemplate.opsForList().leftPushAll(key, collect);
                }
            }
        });
    }

    //2、缓存活动的关联商品信息
    private void saveSessionSkuInfos(List<SeckillSessionsWithSkusVo> sessions) {
        sessions.stream().forEach(session -> {
            //准备has操作
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(item -> {
                String randomCode = UUID.randomUUID().toString().replace("_", "");
                if (!ops.hasKey(item.getPromotionSessionId().toString() + "_" + item.getSkuId().toString())) {
                    //缓存活动的关联商品信息
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    //1、sku的基本信息
                    R info = null;
                    try {
                        info = productFeignService.info(item.getSkuId());
                        log.info("活动的关联商品信息:" + JSONObject.toJSONString(info));
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new NullPointerException("product容器接口/product/skuinfo/info/{skuId}没有上线");
                    }
                    if (info.getCode() == 0) {
                        SkuInfoVo date = info.getDate("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
<<<<<<< HEAD
                        redisTo.setSkuInfoVo(date);

=======
                        redisTo.setSkuInfo(date);
>>>>>>> kill
                    }

                    //2、sku的秒杀信息
                    redisTo.setSeckillLimit(1);//设置秒杀数量1
                    BeanUtils.copyProperties(item, redisTo);

                    //3、设置上当前商品的秒杀的时间信息
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());

                    //4、随机码  seckill?skuId=1&key=jojojoji
                    redisTo.setRandomCode(randomCode);

                    String s = JSON.toJSONString(redisTo);
                    log.info("缓存的商品信息:" + "[key] " + item.getSkuId().toString() + "[info]:" + s);
                    ops.put(item.getPromotionSessionId().toString() + "_" + item.getSkuId().toString(), s);

                    //5、使用库存作为分布式的信号量 限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                    //商品可以秒杀的数量作为信号
                    semaphore.trySetPermits(item.getSeckillCount());
                }
            });
        });
    }
}
